<template>
    <div class="short-link-stats">
        <div class="stats-header">
            <h3 class="stats-title">短链接统计</h3>
            <el-button size="small" text @click="$emit('close')">
                <el-icon>
                    <Close />
                </el-icon>
            </el-button>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
            <div class="loading-spinner"></div>
            <p>正在加载统计数据...</p>
        </div>

        <!-- 统计内容 -->
        <div v-else>

            <!-- 总体统计 -->
            <div class="stats-section">
                <h4 class="section-title">总体统计</h4>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <View />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ totalVisits }}</div>
                            <div class="stat-label">总访问量</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <User />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ totalVisitors }}</div>
                            <div class="stat-label">总访客数</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <Monitor />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ totalIPs }}</div>
                            <div class="stat-label">总IP数</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 今日统计 -->
            <div class="stats-section">
                <h4 class="section-title">今日统计</h4>
                <div class="stats-grid">
                    <div class="stat-card today">
                        <div class="stat-icon">
                            <el-icon>
                                <View />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ todayVisits }}</div>
                            <div class="stat-label">今日访问</div>
                        </div>
                    </div>
                    <div class="stat-card today">
                        <div class="stat-icon">
                            <el-icon>
                                <User />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ todayVisitors }}</div>
                            <div class="stat-label">今日访客</div>
                        </div>
                    </div>
                    <div class="stat-card today">
                        <div class="stat-icon">
                            <el-icon>
                                <Monitor />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ todayIPs }}</div>
                            <div class="stat-label">今日IP数</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 访问排序统计 -->
            <div class="stats-section">
                <h4 class="section-title">访问排序统计</h4>
                <div class="sort-stats-grid">
                    <!-- 操作系统统计 -->
                    <div class="sort-stat-item">
                        <SortableList title="操作系统" :items="osStats" :maxItems="5" defaultSort="desc" />
                    </div>

                    <!-- 浏览器统计 -->
                    <div class="sort-stat-item">
                        <SortableList title="访问浏览器" :items="browserStats" :maxItems="5" defaultSort="desc" />
                    </div>

                    <!-- 设备统计 -->
                    <div class="sort-stat-item">
                        <SortableList title="设备类型" :items="deviceStats" :maxItems="5" defaultSort="desc" />
                    </div>

                    <!-- 网络统计 -->
                    <div class="sort-stat-item">
                        <SortableList title="网络类型" :items="networkStats" :maxItems="5" defaultSort="desc" />
                    </div>
                </div>
            </div>

            <!-- 访问趋势图 -->
            <div class="stats-section">
                <h4 class="section-title">访问趋势</h4>
                <div class="chart-container">
                    <LineChart :data="visitTrendData" :series="visitTrendSeries" :height="200" :showGrid="true"
                        :showLegend="true" :smooth="true" />
                </div>
            </div>

            <!-- 地理分布图 -->
            <div class="stats-section">
                <h4 class="section-title">地理分布</h4>
                <div class="map-container">
                    <ChinaMap title="访问量地理分布" :data="geographicData" :height="300" theme="blue" :showLegend="true"
                        :showLabels="false" :enableZoom="true" :showBoundary="true" />
                </div>
            </div>

            <!-- 访问量柱状图 -->
            <div class="stats-section">
                <h4 class="section-title">访问量统计</h4>
                <div class="chart-container">
                    <BarChart :data="barChartData" :series="barChartSeries" title="24小时访问量分布" :height="200"
                        :showLegend="true" :showLabel="true" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { Close, View, User, Monitor } from '@element-plus/icons-vue'
import LineChart from './charts/LineChart.vue'
import BarChart from './charts/BarChart.vue'
import SortableList from './charts/SortableList.vue'
import ChinaMap from './charts/ChinaMap.vue'
import type { ShortLink, LinkGroup } from '@/api'
import { getLinkStats } from '@/api/shortlink'
import { getBrowserIcon, getOsIcon, getDeviceIcon, getNetworkIcon } from '@/assets/img'

// 定义组件属性
interface Props {
    shortUrl: string
    shortLinks: ShortLink[]
    linkGroups: LinkGroup[]
}

// 定义统计数据类型
interface TotalStats {
    pv: number
    uv: number
    uip: number
}

interface DailyStats {
    pv: number
    uv: number
    uip: number
    date: string
}

interface ChinaStats {
    region: string
    count: number
    ratio: number
}

interface BrowserStats {
    browser: string
    count: number
    ratio: number
}

interface OsStats {
    os: string
    count: number
    ratio: number
}

interface DeviceStats {
    device: string
    count: number
    ratio: number
}

interface NetworkStats {
    network: string
    count: number
    ratio: number
}

interface LinkStatsResponse {
    totalStats: TotalStats[]
    dailyStats: DailyStats[]
    hourStats: number[]  // 24小时访问量数组
    chinaStats: ChinaStats[]
    browserStats: BrowserStats[]
    osStats: OsStats[]
    deviceStats: DeviceStats[]
    networkStats: NetworkStats[]
}

// 定义事件
interface Emits {
    (e: 'close'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 统计数据
const linkStats = ref<LinkStatsResponse | null>(null)
const loading = ref(false)

// 计算总体统计
const totalLinks = computed(() => props.shortLinks.length)
const totalVisits = computed(() => linkStats.value?.totalStats[0]?.pv || 0)
const totalVisitors = computed(() => linkStats.value?.totalStats[0]?.uv || 0)
const totalIPs = computed(() => linkStats.value?.totalStats[0]?.uip || 0)

// 计算今日统计（使用最新一天的数据）
const todayVisits = computed(() => {
    if (!linkStats.value?.dailyStats.length) return 0
    const latestDay = linkStats.value.dailyStats[linkStats.value.dailyStats.length - 1]
    return latestDay.pv
})
const todayVisitors = computed(() => {
    if (!linkStats.value?.dailyStats.length) return 0
    const latestDay = linkStats.value.dailyStats[linkStats.value.dailyStats.length - 1]
    return latestDay.uv
})
const todayIPs = computed(() => {
    if (!linkStats.value?.dailyStats.length) return 0
    const latestDay = linkStats.value.dailyStats[linkStats.value.dailyStats.length - 1]
    return latestDay.uip
})

// 操作系统统计数据
const osStats = computed(() => {
    if (!linkStats.value?.osStats) return []
    return linkStats.value.osStats.map((item, index) => ({
        id: index + 1,
        name: getOsDisplayName(item.os),
        value: Math.round(item.ratio * 100),
        iconUrl: getOsIcon(item.os),
        count: item.count
    }))
})

// 浏览器统计数据
const browserStats = computed(() => {
    if (!linkStats.value?.browserStats) return []
    return linkStats.value.browserStats.map((item, index) => ({
        id: index + 1,
        name: getBrowserDisplayName(item.browser),
        value: Math.round(item.ratio * 100),
        iconUrl: getBrowserIcon(item.browser),
        count: item.count
    }))
})

// 访问趋势数据（使用API返回的真实数据）
const visitTrendData = computed(() => {
    if (!linkStats.value?.dailyStats) return []
    return linkStats.value.dailyStats.map((item) => ({
        name: formatDate(item.date),
        pv: item.pv,
        uv: item.uv,
        uip: item.uip
    }))
})

// 访问趋势系列配置
const visitTrendSeries = ref([
    { key: 'pv', name: '访问量(PV)', color: '#409eff', symbol: 'circle' },
    { key: 'uv', name: '访客数(UV)', color: '#67c23a', symbol: 'diamond' },
    { key: 'uip', name: 'IP数(UIP)', color: '#e6a23c', symbol: 'triangle' }
])

// 柱状图数据 - 24小时访问量
const barChartData = computed(() => {
    if (!linkStats.value?.hourStats) return []
    return linkStats.value.hourStats.map((count, hour) => ({
        name: `${hour}:00`,
        visits: count
    }))
})

// 柱状图系列配置
const barChartSeries = ref([
    { key: 'visits', name: '访问量', color: '#409eff' }
])

// 地理分布数据（使用API返回的真实数据）
const geographicData = computed(() => {
    if (!linkStats.value?.chinaStats) return []
    return linkStats.value.chinaStats.map((item) => ({
        name: getRegionDisplayName(item.region),
        value: item.count,
        description: `${item.region}`,
        unit: '次'
    }))
})

// 设备统计数据
const deviceStats = computed(() => {
    if (!linkStats.value?.deviceStats) return []
    return linkStats.value.deviceStats.map((item, index) => ({
        id: index + 1,
        name: getDeviceDisplayName(item.device),
        value: Math.round(item.ratio * 100),
        iconUrl: getDeviceIcon(item.device),
        count: item.count
    }))
})

// 网络统计数据
const networkStats = computed(() => {
    if (!linkStats.value?.networkStats) return []
    return linkStats.value.networkStats.map((item, index) => ({
        id: index + 1,
        name: getNetworkDisplayName(item.network),
        value: Math.round(item.ratio * 100),
        iconUrl: getNetworkIcon(item.network),
        count: item.count
    }))
})

// 辅助函数
const getOsDisplayName = (os: string): string => {
    const osMap: Record<string, string> = {
        'android': 'Android',
        'windows': 'Windows',
        'ios': 'iOS',
        'macos': 'macOS',
        'linux': 'Linux',
        'harmony': 'HarmonyOS'
    }
    return osMap[os] || os
}

const getBrowserDisplayName = (browser: string): string => {
    const browserMap: Record<string, string> = {
        'chrome': 'Chrome浏览器',
        'edge': 'Edge浏览器',
        'firefox': 'Firefox浏览器',
        'safari': 'Safari浏览器',
        'opera': 'Opera浏览器'
    }
    return browserMap[browser] || browser
}

// 使用统一的图片资源函数

const getDeviceDisplayName = (device: string): string => {
    const deviceMap: Record<string, string> = {
        'mobile': '移动设备',
        'pc': '桌面设备',
        'pad': '平板设备',
        'tablet': '平板设备'
    }
    return deviceMap[device] || device
}

const getNetworkDisplayName = (network: string): string => {
    const networkMap: Record<string, string> = {
        'broadband': '宽带网络',
        'mobile': '移动网络',
        'wifi': 'WiFi网络',
        'wireless': '无线网络'
    }
    return networkMap[network] || network
}

const formatDate = (dateStr: string): string => {
    const date = new Date(dateStr)
    const month = date.getMonth() + 1
    const day = date.getDate()
    // 使用更友好的日期格式，如 "8月16日" 或 "08-16"
    return `${month}月${day}日`
}

const getRegionDisplayName = (region: string): string => {
    // 处理省份名称，移除后缀并优化显示
    return region
        .replace('省', '')
        .replace('市', '')
        .replace('自治区', '')
        .replace('特别行政区', '')
}

// 组件挂载时获取统计信息
onMounted(async () => {
    if (props.shortUrl) {
        try {
            loading.value = true
            const response = await getLinkStats(props.shortUrl)
            linkStats.value = response
        } catch (error) {
            console.error('获取短链接统计信息失败:', error)
        } finally {
            loading.value = false
        }
    }
})
</script>

<style scoped>
.short-link-stats {
    padding: 20px;
    height: 100%;
    overflow-y: auto;
    background: #fff;
}

.stats-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e9ecef;
}

.stats-title {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
    text-align: center;
    flex: 1;
}

.stats-section {
    margin-bottom: 24px;
}

.section-title {
    margin: 0 0 16px 0;
    font-size: 14px;
    font-weight: 500;
    color: #666;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
}

.stat-card {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    display: flex;
    align-items: center;
    gap: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e9ecef;
    transition: all 0.2s ease;
    position: relative;
    overflow: hidden;
    min-width: 0;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card.today {
    border-color: #409eff;
    background: linear-gradient(135deg, #f0f8ff 0%, #e6f7ff 100%);
}

.stat-card.today::before {
    background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
}

.stat-icon {
    width: 36px;
    height: 36px;
    border-radius: 6px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 16px;
    flex-shrink: 0;
}

.stat-content {
    flex: 1;
    min-width: 0;
    overflow: hidden;
}

.stat-number {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    line-height: 1;
    margin-bottom: 2px;
    white-space: nowrap;
}

.stat-label {
    font-size: 11px;
    color: #666;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    white-space: nowrap;
}

/* 排序统计网格 */
.sort-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
    gap: 20px;
}

.sort-stat-item {
    min-height: 200px;
}

.chart-container {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e9ecef;
}

.map-container {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e9ecef;
    min-height: 350px;
}

/* 加载状态样式 */
.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;
}

.loading-container p {
    margin-top: 16px;
    color: #666;
    font-size: 14px;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #409eff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .short-link-stats {
        padding: 16px;
    }

    .stats-grid {
        grid-template-columns: 1fr;
        gap: 8px;
    }

    .sort-stats-grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }

    .stat-card {
        padding: 12px;
    }

    .stat-number {
        font-size: 18px;
    }
}

@media (max-width: 480px) {
    .stats-grid {
        grid-template-columns: 1fr;
        gap: 6px;
    }

    .sort-stats-grid {
        gap: 12px;
    }

    .stat-card {
        padding: 10px;
    }

    .stat-icon {
        width: 32px;
        height: 32px;
        font-size: 14px;
    }

    .stat-number {
        font-size: 16px;
    }

    .stat-label {
        font-size: 10px;
    }
}
</style>
